// miniprogram/pages/mine/activity/list/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isEmpty: false,
    total: 0,
    page: 1,
    pageSize: 20,
    activities:[]
  },

  getActivities: function () {
    const db = wx.cloud.database();
    const _ = db.command;
    this.setData({
      page: 1,
      pagesize: 20,
    });

    db.collection('activity').limit(20).get({
      success: res => {
        console.log(res.data);
        if (res.data.length == 0) {
          this.setData({ isEmpty: true })
        } else {
          this.setData({ isEmpty: false })
        }
        this.setData({ activities: res.data })
      }
    });
  },
  onClickAdd:function(){
    wx.navigateTo({
      url: '../add/index',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  onClickItem: function(e){
    var activity = e.currentTarget.dataset.activity
    wx.navigateTo({
      url: '../qrcode/index?id=' + activity._id+'&name=' + activity.name + '&beginTime=' + activity.beginTime+'&endTime=' + activity.endTime,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   this.getActivities()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      page: 1,
      pagesize: 20,
    });
    const db = wx.cloud.database();
    wx.showNavigationBarLoading() //在标题栏中显示加载
    db.collection('activity').limit(20).get({
      success: res => {
        console.log(res.data);
        if (res.data.length == 0) {
          this.setData({ isEmpty: true })
        } else {
          this.setData({ isEmpty: false })
        }
        this.setData({ activities: res.data })
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.data.page++
    this.setData({
      page: this.data.page,
      pagesize: 20
    });
    const db = wx.cloud.database();
    let skip = (this.data.page - 1) * 20
    console.log("skip", skip)
    db.collection('activity').skip(skip).limit(20).get({
      success: res => {
        if (res.data.length == 0) {
          this.data.page--
          this.setData({
            page: this.data.page
          });
        } else {
          this.setData({ activities: this.data.activities.concat(res.data) })
        }
      }
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})